{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#  从视频流中采集目标对象的人脸，用于训练分类模型，这个模型用于主程序中摄像头实时视频中人脸识别出目标对象\n",
    "#  每1帧采集一张人脸，一共采集100个目标对象的样本，使用mtcnn对采集帧进行人脸检测和对齐\n",
    "\n",
    "import cv2\n",
    "import sys\n",
    "import os\n",
    "import tensorflow as tf\n",
    "import numpy as np\n",
    "import align.detect_face\n",
    "import facenet\n",
    "\n",
    "video_capture = cv2.VideoCapture(0)\n",
    "capture_interval = 1\n",
    "capture_num = 100\n",
    "capture_count = 0\n",
    "frame_count = 0\n",
    "detect_multiple_faces = False #因为是训练目标对象，一次只有一张人脸\n",
    "\n",
    "#这里引用facenet/src/align/align_dataset_mtcnn.py文件的代码对采集帧进行人脸检测和对齐\n",
    "minsize = 20 # minimum size of face\n",
    "threshold = [ 0.6, 0.7, 0.7 ]  # three steps's threshold\n",
    "factor = 0.709 # scale factor\n",
    "        \n",
    "with tf.Graph().as_default():\n",
    "    gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.5)\n",
    "    sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options, log_device_placement=False))\n",
    "    with sess.as_default():\n",
    "        pnet, rnet, onet = align.detect_face.create_mtcnn(sess, None)\n",
    "\n",
    "while True:\n",
    "\n",
    "    ret, frame = video_capture.read()\n",
    "    \n",
    "    #每1帧采集一张人脸，这里采样不进行灰度变换，直接保存彩色图\n",
    "    if(capture_count%capture_interval == 0): \n",
    "        \n",
    "        bounding_boxes, _ = align.detect_face.detect_face(frame, minsize, pnet, rnet, onet, threshold, factor)\n",
    "        nrof_faces = bounding_boxes.shape[0]\n",
    "                          \n",
    "        for face_position in bounding_boxes: #因为只采集一张人脸，所以实际只遍历一次\n",
    "            face_position=face_position.astype(int)\n",
    "            cropped = frame[face_position[1]:face_position[3],face_position[0]:face_position[2],:]\n",
    "            scaled = cv2.resize(cropped, (160, 160), interpolation=cv2.INTER_CUBIC )  #这里取和负样本一样大小\n",
    "            cv2.imwrite('/Users/admin/Desktop/abby'+str(frame_count) + '.jpg', scaled)\n",
    "                                \n",
    "        frame_count += 1\n",
    "          \n",
    "    capture_count += 1\n",
    "   \n",
    "    if frame_count >= capture_num:\n",
    "        break\n",
    "\n",
    "video_capture.release()\n",
    "cv2.destroyAllWindows()\n",
    "print('采集完成')"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
